package com.itheima.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.jni.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查找所有用户
     * @return  list<User>
     */
    @GetMapping("/findAll")
    public List<User> findAll(){
        return userService.findAll();

    }

    /**
     * 增加了缓存的查询所有用户的请求资源
     * @return
     */
    @GetMapping("/findAllCache")
    public String findAllCache() throws JsonProcessingException{
        //1.查询redis缓存
        //2.存在返回
        //3.不存在--->mysql数据库查找--->转为json字符串存入redis--->返回
        String usersStr = "";
        usersStr = (String) redisTemplate.boundValueOps("userAll364").get();

        /*if (null != usersStr && ""  != usersStr){

        }*/
        if (StringUtils.isEmpty(usersStr)){//不存在
            log.info("............从musql数据库中查找.................");
            //不存在--->mysql数据库查找--->转为json字符串存入redis--->返回
            List<User> userList = userService.findAll();
            ObjectMapper objectMapper = new ObjectMapper();
            usersStr = objectMapper.writeValueAsString(userList);
            redisTemplate.boundValueOps("userAll364").set(usersStr);

        }

       return usersStr;

    }
}
